package com.qiangesoft.blog.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiangesoft.blog.common.constants.FieldConstants;
import com.qiangesoft.blog.common.mvc.PageQuery;
import com.qiangesoft.blog.common.mvc.PageResultVO;
import com.qiangesoft.blog.common.result.ResponseResult;
import com.qiangesoft.blog.core.entity.BlogFriendChain;
import com.qiangesoft.blog.core.mapper.BlogFriendChainMapper;
import com.qiangesoft.blog.core.service.IBlogFriendChainService;
import com.qiangesoft.blog.system.email.EmailService;
import com.qiangesoft.blog.system.pojo.vo.BlogFriendChainVO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;

import static com.qiangesoft.blog.common.enums.FriendLinkEnum.APPLY;
import static com.qiangesoft.blog.common.enums.FriendLinkEnum.UP;

/**
 * <p>
 * 友情链接 服务实现类
 * </p>
 *
 * @author qiange
 * @since 2023-06-05
 */
@Service
@RequiredArgsConstructor
public class BlogFriendChainServiceImpl extends ServiceImpl<BlogFriendChainMapper, BlogFriendChain> implements IBlogFriendChainService {

    private final EmailService emailService;

    @Override
    public PageResultVO<BlogFriendChain> listFriendLink(PageQuery pageQuery, String name, Integer status) {
        PageResultVO<BlogFriendChain> pageResultVO = new PageResultVO<>();
        Integer pageNum = pageQuery.getPageNum();
        Integer pageSize = pageQuery.getPageSize();
        pageResultVO.setPageNum(pageNum);
        pageResultVO.setPageSize(pageSize);

        QueryWrapper<BlogFriendChain> queryWrapper = new QueryWrapper<BlogFriendChain>()
                .orderByDesc(FieldConstants.SORT).like(StringUtils.isNotBlank(name), FieldConstants.NAME, name)
                .eq(status != null, FieldConstants.STATUS, status);
        Page<BlogFriendChain> page = baseMapper.selectPage(new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize()), queryWrapper);
        pageResultVO.setTotal(page.getTotal());
        pageResultVO.setPages(page.getPages());
        pageResultVO.setResults(page.getRecords());
        return pageResultVO;
    }

    /**
     * 添加友链
     *
     * @param friendLink
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult insertFriendLink(BlogFriendChain friendLink) {
        baseMapper.insert(friendLink);
        return ResponseResult.success();
    }

    /**
     * 修改友链
     *
     * @param friendLink
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateFriendLink(BlogFriendChain friendLink) {
        baseMapper.updateById(friendLink);
        //审核通过和未通过发送邮件通知
        emailService.friendFailedSendEmail(friendLink.getEmail(), friendLink.getReason());
        return ResponseResult.success();
    }

    /**
     * 删除友链
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult deleteBatch(List<Integer> ids) {
        int rows = baseMapper.deleteBatchIds(ids);
        return rows > 0 ? ResponseResult.success() : ResponseResult.error("删除友链失败");
    }

    /**
     * 置顶友链
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult top(Long id) {
        Integer sort = baseMapper.getMaxSort();
        baseMapper.top(id, sort + 1);
        return ResponseResult.success();
    }

    //    ---------web端方法开始------

    /**
     * 友链列表
     *
     * @return
     */
    @Override
    public List<BlogFriendChainVO> webFriendLinkList() {
        return baseMapper.selectLinkList(UP.code);
    }

    /**
     * 申请友链
     *
     * @param friendLink
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void applyFriendLink(BlogFriendChain friendLink) {
        Assert.isTrue(StringUtils.isNotBlank(friendLink.getUrl()), "输入正确的网址!");
        friendLink.setStatus(APPLY.getCode());

        Assert.isTrue(!friendLink.getUrl().contains("shiyit.com") &&
                !friendLink.getUrl().contains("baidu.com"), "不合法的网址！");

        //如果已经申请过友链 再次接入则会进行下架处理 需重新审核
        BlogFriendChain entity = baseMapper.selectOne(new QueryWrapper<BlogFriendChain>()
                .eq(FieldConstants.URL, friendLink.getUrl()));
        if (entity != null) {
            friendLink.setId(entity.getId());
            baseMapper.updateById(friendLink);
        } else {
            baseMapper.insert(friendLink);
        }
        //异步操作邮箱发送
        emailService.emailNoticeMe("友链接入通知", "网站有新的友链接入啦(" + friendLink.getUrl() + ")，快去审核吧!!!");
    }
}
